package com.Cychat.post.service.impl;


import com.Cychat.commons.entity.pojo.Comment;
import com.Cychat.commons.entity.pojo.Post;
import com.Cychat.post.entity.dto.CommentDTO;
import com.Cychat.post.entity.mq.CollectMonitor;
import com.Cychat.post.entity.mq.CommentMonitor;
import com.Cychat.post.entity.vo.CommentVO;
import com.Cychat.post.mapper.CommentMapper;
import com.Cychat.post.mapper.PostMapper;
import com.Cychat.post.service.CommentService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Auther: 崔航
 * @Date: 2025/10/28:14:28
 * @Description:
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public List<Comment> getCommentsByPostId(Integer postId) {
       return commentMapper.getCommentsByPostId(postId);
    }

    @Override
    public List<CommentDTO> getCommentsByRootId(Integer rootId) {
        return commentMapper.getCommentsByRootId(rootId);
    }


    @Override
    public Integer addComment(CommentVO commentVO) {
        Comment comment = new Comment();
        comment.setUserId(commentVO.getUserId());
        comment.setPostId(commentVO.getPostId());
        comment.setRootId(commentVO.getRootId());
        comment.setParentId(commentVO.getParentId());
        comment.setContent(commentVO.getContent());
        comment.setLevel(commentVO.getRootId() == null ? 1 : 2);
        comment.setLikeCount(0);
        comment.setStatus(1);
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());
        this.save(comment);
        // 新增：更新对应帖子的评论数（自增1）
        Integer postId = commentVO.getPostId(); // 获取帖子ID
        if (postId != null) { // 避免空指针，确保帖子ID存在
            LambdaUpdateWrapper<Post> lambdaWrapper = new LambdaUpdateWrapper<>();
            lambdaWrapper.eq(Post::getPostId, postId) // 条件：匹配帖子ID
                    .setSql("comment_count = comment_count + 1"); // 自增逻辑
            postMapper.update(null, lambdaWrapper); // 执行更新
        }
        // 新增：发送消息给MQ
        CommentMonitor monitor = new CommentMonitor(commentVO.getUserId(), commentVO.getPostId(), commentVO.getContent(), commentVO.getParentId());
        rabbitTemplate.convertAndSend("cychat.exchange","comment",monitor);
        return comment.getCommentId();
    }

    @Override
    public Comment getCommentById(Integer commentId) {
        return commentMapper.getCommentById(commentId);
    }
}
